#!/bin/bash

# ******************************************
# Resize Linux ext4 partition to fill sdcard
# ******************************************

if [ "$(id -u)" != "0" ]; then
	echo "Script must be run as root !"
	exit 0
fi

_rootpart=`mount | grep "on / " | awk '{print $1}'`
if [ "${_rootpart}" = "/dev/mmcblk0p2" ]; then
        rootdrv="mmcblk0p2"
        sdcard="/dev/mmcblk0"
elif [ "${_rootpart}" = "/dev/mmcblk1p2" ]; then
        rootdrv="mmcblk1p2"
        sdcard="/dev/mmcblk1"
else
        echo "Root fs mount partition not found!"
        exit 1
fi
echo ""

fdisk -l $sdcard | grep $sdcard
echo ""
sdcard_part=`fdisk -l $sdcard | grep $rootdrv | awk '{print $1}'`
sdcard_sect=`fdisk -l $sdcard | grep "Disk $sdcard" | awk '{print $7}'`
if [ "${sdcard_sect}" = "" ]; then
    sdcard_sect=`fdisk -l $sdcard | grep total | awk '{print $8}'`
fi
sdcard_end=$(expr $sdcard_sect - 1024)

part_start=`fdisk -l $sdcard | grep $rootdrv | awk '{print $2}'`
part_end=`fdisk -l $sdcard | grep $rootdrv | awk '{print $3}'`

echo "	Max block: $sdcard_end"
echo "	Part end: $part_end"
echo "	Part start: $part_start"

echo ""
if [ $part_end -ge $sdcard_end ]; then
    echo "Partition allready maximum size !"
    exit 0
fi

read -p "Do you want to resize $sdcard_part (y/n)?" continue
if [ ! "$continue" = "y" ] ; then
    echo ""
    echo "Canceled.."
    exit 0
fi
echo ""

# RESIZE PARTITION
echo "resize partiton"
echo -e "p\nd\n2\nn\np\n2\n$part_start\n$sdcard_end\nw" | fdisk ${sdcard} > /dev/null 2>&1
resize2fs $rootdrv

fdisk -l ${sdcard}
#if [ $? -ne 0 ]; then
#	echo "ERROR resizing partition!"
#	exit 1
#fi

echo ""
echo "Rootfs Extended. Please REBOOT to take effect"
read -p "Press any key to reboot :" 
shutdown -r now

